package br.com.opet.DAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import br.com.opet.vo.*;

public class UsuarioDAO {
	public static boolean insert(Admin admin)
	{
		try{
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.persist(admin);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
	
	public static boolean remove(int idUsuario)
	{
		try{
			Usuario us = SearchById(idUsuario);		
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.remove(us);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
	
	public static Admin SearchById(int idUsuario)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Admin where id = :idP");
			q.setParameter("idP", idUsuario);
			List<Admin> usuarios = q.getResultList();
			if(!usuarios.isEmpty()){
				return usuarios.get(0);								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static Admin SearchByEmail(Admin admin)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Admin where email = :emailP");
			q.setParameter("emailP", admin.getEmail());
			List<Admin> usuarios = q.getResultList();
			if(!usuarios.isEmpty()){
				return usuarios.get(0);								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static List<Admin> listAll()
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Admin order by nome");
			List<Admin> usuarios = q.getResultList();
			if(!usuarios.isEmpty()){
				return usuarios;								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static Admin checkUser(Admin usuario)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Usuario where email = :emailP ");
			q.setParameter("emailP", usuario.getEmail());
			List<Admin> usuarios = q.getResultList();
			if(!usuarios.isEmpty()){
				if(usuarios.get(0).getSenha().equals(usuario.getSenha()))
				{
					return usuarios.get(0);
				}
				else
				{
					return null;
				}				
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
}
